


import os
import sys

from Cheetah.Template import Template

import table_meta as meta
from utils import mc


class Vmgen:
  def __init__(self):
    uri = 'sqlite:///data02.dm1'
    
    self.mc = mc.MC() 
    
    self.db = meta.DB(uri, False)
    
  def getmsgdict(self):
    sql ="select tablename, name, attribute  from columns where column_type != 'auto' and column_type != '' order by tablename, ordering asc "
    result = self.db.execute(sql)
    messages = {}
    #ukey = set()
    i = 0
    for row in result.fetchall():
      #print row[1].encode('utf8')
      i = i+1
      key = row[1].lower()
      value = repr(row[2]).replace("u'","")
      value = value.replace("'","")
      messages[key] = value
    
    #print messages
    return messages
    
  def propertiesGen(self):
    pathin  =  'mod_template/java/vm/edit.vm'
    pathout = 'editg.vm'
    output = open(pathout, 'w') 
    sp = Template(file=pathin)
    sp.messages = messages
    sp = "%s" %(sp)
    sp = sp.encode('utf8')
    print sp
    output.writelines(sp)

  def getTables(self):
    sql = "select NAME, TABLE_TYPE from TABLES"
    result = self.db.execute(sql)
    self.tables = []
    self.entities = []
    #print "<table>"
    
    for row in result.fetchall():
      table = {}
      table['name'] = row[0]
      table['type'] = row[1]
      self.tables.append(table)
      
      self.entities.append({'name':row[0].capitalize()[:-1], "type":row[1]})
    self.vmlistgen()
    #print self.tables;
  
  def vmlistgen(self):
      
      pathin  =  'mod_template/java/vm/struts-config-module.xml'
      pathout = '\\gen\\struts-config.xml'
      messages = None
      entity = self.entities
      self.output(pathin, pathout, messages, entity)
      
    
  def gen(self):
    #print self.tables
    for table in self.tables:
      self.getCol(table)
      #print item

  def naming(self, name):
    #name = name.lower()
    name = name.capitalize()
    return name
    
    items = name.split("_")
    if len(name)>1:
      name = ""
      i =0
      for part in items:
        if i > 0:
          name = name+part.capitalize()
        else:
          name = name + part
        i = i+1
        
    return name

  def tuple2dict(self, tuples, names):
    if len(tuples) == len(names):
      dict = {}
      i = 0
      for item in names:
        #print type(tuples[i])
        if item == 'name' and isinstance (tuples[i],unicode):
            #print "unicode>>>>>>"
            #print tuples[i].encode('utf8')
            if tuples[i].find('PK_') == 0:                
                dict[item] = "Id"
            else:
                dict[item] = tuples[i]
        else:
            dict[item] = tuples[i]
        i = i+1       
      #print dict
      return dict
    else:
      print "ERROR! length not match"
    

  def getCol(self, table):
    sql ="select name, attribute,DATA_TYPE, not_null, width, ispk, isfk  from columns where column_type != 'auto' and tablename ='%s' order by ordering asc " %(table['name'])
    #print sql    
    result = self.db.execute(sql)
    if result != None:
      i = 0
      messages = []
      for row in result.fetchall():
        i = i +1
        #print row[0], i, row[1], row[2].encode('utf8')
        names = ('name', 'attribute','data_type', 'not_null', 'width', 'ispk', 'isfk')
        dict = self.tuple2dict(row, names)
        
        ## deal with naming :
        
        dict['name'] = dict['name'].lower()
        dict['name'] = dict['name'].replace('_','')
        #dict['name'] = self.naming(dict['name'])
        #item = (self.naming(row[0]), row[1], row[2])
        #print "dict >>>>>>>>>>>"
        #print dict
        messages.append(dict)
      entity = {}
      entity['name'] = table['name'].lower()[:-1]        
      entity['type'] = table['type']
        
      pathin  =  'mod_template/java/vm/edit.vm'
      pathout = '\\gen\\%s\\%s\\edit%s.vm' %(table['type'], table['name'].capitalize()[:-1],table['name'].capitalize()[:-1])      
      self.output(pathin, pathout, messages, entity)
      
      pathin  =  'mod_template/java/vm/view.vm'
      pathout = '\\gen\\%s\\%s\\view%s.vm' %(table['type'], table['name'].capitalize()[:-1],table['name'].capitalize()[:-1])
      self.output(pathin, pathout, messages, entity)
      
      pathin  =  'mod_template/java/vm/show.vm'
      pathout = '\\gen\\%s\\%s\\show%s.vm' %(table['type'], table['name'].capitalize()[:-1],table['name'].capitalize()[:-1])
      self.output(pathin, pathout, messages, entity)      

      pathin  =  'mod_template/java/vm/add.vm'
      pathout = '\\gen\\%s\\%s\\add%s.vm' %(table['type'], table['name'].capitalize()[:-1],table['name'].capitalize()[:-1])      
      self.output(pathin, pathout, messages, entity)     
      
  def output(self, pathin, pathout, messages, entity):
    #print pathin
    pathout = os.getcwd() + pathout
    basedir = os.path.dirname(pathout).lower()
    #pathin = self.pathfilter(pathin)
    
    self.mc.mkdir(basedir)
    
    output = open(pathout, 'w')  
    sp = Template(file=pathin)
    sp.messages = messages
    sp.table = entity
    
    sp = "%s"%(sp)
    sp = sp.encode('utf8')
    output.writelines(sp)

  def run(self):
    pathin  =  'mod_template/java/vm/editp.vm'
    pathout = 'editp.vm'
    output = open(pathout, 'w') 
    sp = Template(file=pathin)
    sp.messages = messages
    sp = "%s" %(sp)
    sp = sp.encode('utf8')
    print sp
    output.writelines(sp)

  def formgen(self, messages):
    pathin  =  'form.tpl'
    pathout = 'form.jsp'
    output = open(pathout, 'w') 
    sp = Template(file=pathin)
    sp.messages = messages
    sp = "%s" %(sp)
    #print sp
    #output.writelines(sp)

  def moutput(self, messages):
    pathin  =  'message_zh_CN.properties.tpl'
    pathout = 'message_zh_CN.properties'
    output = open(pathout, 'w') 
    sp = ""
    for item in messages:
      str = "msg.%s.%s = %s\n" %(item[0], item[1], item[2])
      output.write(str.encode('utf8'))
      
    #output.writelines(sp)

if __name__ == "__main__":
    vg = Vmgen()
    vg.getTables()
    vg.gen()
